package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptService  deptService;



    @Override
    public PageResult<Emp> page(EmpQueryParam param) {
        Page<Emp> objectPage = Page.of(param.getPage(), param.getPageSize());
        //根据最后修改时间倒序排序
        objectPage.addOrder(OrderItem.desc("update_time"));

        Page<Emp> page = page(objectPage);
        // 获取员工集合
        List<Emp> emps = page.getRecords();

        // 构建查询条件
        // 使用lambdaQuery方法构建查询条件
        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);
        // 获取所有员工的部门id
        List<Integer> ids = emps.stream().map(emp -> emp.getDeptId()).toList();

        // 批量查询这些部门的信息
        List<Dept> depts = deptService.listByIds(ids);
        Map<Integer, String> deptMap = depts.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
        // 将部门名称封装到员工对象中
        emps.stream().forEach(emp -> {
            Integer deptId = emp.getDeptId();//通过员工表获得部门id
          //map<id,name> 所以通过部门id获得部门名称
          String deptName=  deptMap.get(deptId);
          if(deptName!=null){
              emp.setDeptName(deptName);
          }
        });
        return new PageResult<>(page.getTotal(), emps);

    }
}
